<template>
  <el-drawer
    v-model="visible"
    title=""
    direction="rtl"
    size="600px"
    class="file-detail-drawer"
  >
    <template #header>
      <div class="drawer-header">
        <div class="drawer-title">
                  <div class="title-bar"></div>
        <span>{{ fileDetail?.filename || fileDetail?.file_name || '文档详情' }}</span>
        </div>
      </div>
    </template>

    <div class="drawer-content">
      <!-- 标签页 -->
      <div class="drawer-tabs">
        <div class="tab-item" :class="{ active: activeTab === 'basic' }" @click="activeTab = 'basic'">基本信息</div>
        <div class="tab-item" :class="{ active: activeTab === 'attachments' }" @click="activeTab = 'attachments'">文档信息</div>
      </div>

      <!-- 基本信息内容 -->
      <div v-if="activeTab === 'basic'" class="basic-info">
        <div class="info-section">
          <div class="info-row">
            <div class="info-label">文档名称：</div>
            <div class="info-value">{{ fileDetail?.filename || fileDetail?.file_name || '-' }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">所属分类：</div>
            <div class="info-value">{{ fileDetail?.file_category_name || '-' }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">上传者：</div>
            <div class="info-value">{{ fileDetail?.uploader || '-' }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">创建时间：</div>
            <div class="info-value">{{ formatCreateTime(fileDetail?.createTime || fileDetail?.create_time) }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">文档描述：</div>
            <div class="info-value">{{ fileDetail?.description || '-' }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">标签：</div>
            <div class="info-value">
              <div v-if="parseStringifiedArray(fileDetail?.label).length > 0" class="tags-container">
                <el-tag
                  v-for="(tag, index) in parseStringifiedArray(fileDetail?.label).slice(0, 3)"
                  :key="tag"
                  size="small"
                  type="primary"
                  effect="light"
                  style="margin-right: 8px; margin-bottom: 4px;"
                >
                  {{ tag }}
                </el-tag>
                <el-tag
                  v-if="parseStringifiedArray(fileDetail?.label).length > 3"
                  size="small"
                  type="info"
                  effect="plain"
                  class="more-tag"
                >
                  +{{ parseStringifiedArray(fileDetail?.label).length - 3 }}
                </el-tag>
              </div>
              <span v-else class="no-data">-</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-label">关键词：</div>
            <div class="info-value">
              <div v-if="parseStringifiedArray(fileDetail?.knowledge_keyword).length > 0" class="keywords-container">
                <el-tag
                  v-for="(keyword, index) in parseStringifiedArray(fileDetail?.knowledge_keyword).slice(0, 3)"
                  :key="keyword"
                  size="small"
                  type="success"
                  effect="light"
                  style="margin-right: 8px; margin-bottom: 4px;"
                >
                  {{ keyword }}
                </el-tag>
                <el-tag
                  v-if="parseStringifiedArray(fileDetail?.knowledge_keyword).length > 3"
                  size="small"
                  type="info"
                  effect="plain"
                  class="more-tag"
                >
                  +{{ parseStringifiedArray(fileDetail?.knowledge_keyword).length - 3 }}
                </el-tag>
              </div>
              <span v-else class="no-data">-</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 当前文档 -->
      <div v-if="activeTab === 'attachments'" class="current-document">
        <div v-if="fileDetail" class="document-item">
          <div class="document-info">
            <div class="document-name">{{ fileDetail.filename || fileDetail.file_name }}</div>
            <div class="document-details">
              <span class="detail-item">文档分类: {{ fileDetail.file_category_name || '未分类' }}</span>
              <span class="detail-item">上传者: {{ fileDetail.uploader || '未知' }}</span>
              <span class="detail-item">创建时间: {{ formatCreateTime(fileDetail.createTime || fileDetail.create_time) }}</span>
              <span class="detail-item upload-status">AI说明: 上传成功</span>
            </div>
          </div>
          <div class="document-actions">
            <el-button
              size="small"
              class="action-btn preview-btn"
              @click="previewCurrentFile"
            >
              预览
            </el-button>
            <el-button
              size="small"
              class="action-btn download-btn"
              @click="downloadCurrentFile"
            >
              下载
            </el-button>
          </div>
        </div>
        <div v-else class="no-document">
          <p>暂无文档信息</p>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { formatCreateTime } from '@/utils/dateFormat'

interface FileDetail {
  id?: number
  filename?: string
  size?: string
  type?: string
  category?: string
  chineseName?: string
  uploader?: string
  createTime?: string
  updateTime?: string
}

interface Props {
  visible: boolean
  fileDetail?: FileDetail | null
  activeDrawerTab?: string
  mockFiles?: any[]
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'update:activeDrawerTab', value: string): void
  (e: 'download', file: any): void
  (e: 'preview', file: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const activeTab = computed({
  get: () => props.activeDrawerTab || 'basic',
  set: (value) => emit('update:activeDrawerTab', value)
})

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 模拟附件数据
const mockFiles = computed(() => props.mockFiles || [
  { name: '6 公文管理标准化手册.docx', category: 'AI说明：上传成功', status: 'success' },
  { name: '5 督查管理.docx', category: 'AI说明：上传成功', status: 'success' },
  { name: '4 档案管理.docx', category: 'AI说明：上传失败', status: 'error' },
  { name: '3 信息管理.docx', category: 'AI说明：上传成功', status: 'success' },
  { name: '2 人事管理.docx', category: 'AI说明：上传成功', status: 'success' },
  { name: '1 财务管理.docx', category: 'AI说明：上传成功', status: 'success' }
])

const downloadFile = (file: any) => {
  emit('download', file)
}

const previewFile = (file: any) => {
  emit('preview', file)
}

// 处理当前文档的预览和下载
const previewCurrentFile = () => {
  if (props.fileDetail) {
    emit('preview', props.fileDetail)
  }
}

const downloadCurrentFile = () => {
  if (props.fileDetail) {
    emit('download', props.fileDetail)
  }
}

// 获取文件类型
const parseStringifiedArray = (value: string[] | string | undefined): string[] => {
  if (!value) return []
  if (Array.isArray(value)) return value
  if (typeof value === 'string') {
    try {
      const trimmed = value.trim()
      if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
        const content = trimmed.slice(1, -1)
        if (content) {
          return content.split(',').map(item =>
            item.trim().replace(/^['"]|['"]$/g, '')
          ).filter(item => item.length > 0)
        }
      }
      return [value]
    } catch (error) {
      console.error('解析字符串化数组失败:', error)
      return [value]
    }
  }
  return []
}

const getFileType = (filename?: string) => {
  if (!filename) return '未知'
  const extension = filename.split('.').pop()?.toLowerCase()
  switch (extension) {
    case 'pdf':
      return 'PDF文档'
    case 'doc':
    case 'docx':
      return 'Word文档'
    case 'xls':
    case 'xlsx':
      return 'Excel表格'
    case 'ppt':
    case 'pptx':
      return 'PowerPoint演示文稿'
    case 'txt':
      return '文本文档'
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
      return '图片文件'
    default:
      return extension?.toUpperCase() + '文件' || '未知类型'
  }
}
</script>

<style scoped>
/* 文件详情抽屉样式 */
:deep(.file-detail-drawer .el-drawer) {
  background: #ffffff;
}

:deep(.file-detail-drawer .el-drawer__header) {
  padding: 0;
  margin-bottom: 0;
  border-bottom: 1px solid #f0f0f0;
}

.drawer-header {
  padding: 20px 24px;
  background: #ffffff;
}

.drawer-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.title-bar {
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  border-radius: 2px;
}

.drawer-content {
  padding: 0 24px 24px;
}

.drawer-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.tab-item {
  padding: 12px 0;
  margin-right: 32px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  position: relative;
  transition: color 0.3s ease;
}

.tab-item.active {
  color: #5b7cff;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  border-radius: 1px;
}

/* 当前文档样式 */
.current-document {
  padding: 16px 0;
}

.document-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.document-info {
  flex: 1;
}

.document-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.4;
}

.document-details {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.detail-item {
  font-size: 13px;
  color: #666;
  display: flex;
  align-items: center;
}

.detail-item::before {
  content: '•';
  color: #5b7cff;
  margin-right: 8px;
  font-weight: bold;
}

.upload-status {
  color: #52c41a;
  font-weight: 500;
}

.upload-status::before {
  color: #52c41a;
}

.document-actions {
  display: flex;
  gap: 12px;
  margin-left: 16px;
  align-items: flex-start;
}

.action-btn {
  font-size: 12px;
  padding: 8px 16px;
  min-width: 60px;
  border-radius: 6px;
  border: 1px solid #a685ff;
  background: linear-gradient(135deg, #f3e8ff 0%, #e8f2ff 100%);
  color: #7c3aed;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: linear-gradient(135deg, #a685ff 0%, #5b7cff 100%);
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(166, 133, 255, 0.3);
}

.no-document {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.no-document p {
  font-size: 14px;
  margin: 0;
}

/* 基本信息样式 */
.basic-info {
  padding: 16px 0;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.info-label {
  min-width: 80px;
  font-size: 14px;
  color: #666;
  font-weight: 500;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.info-value .el-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.tags-container,
.keywords-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.more-tag {
  font-size: 11px;
  padding: 2px 6px;
  height: 20px;
  line-height: 16px;
}

.no-data {
  color: #999;
  font-style: italic;
}
</style>
